<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px;">
      <detail-list title="基本信息">
        <detail-list-item term="活动编号">{{ info.id }}</detail-list-item>
        <detail-list-item term="状态">{{ status }}</detail-list-item>
        <detail-list-item term="商品名称">{{ info.commodity && info.commodity.name }}</detail-list-item>
        <detail-list-item term="商品编号">{{ info.commodity && info.commodity.numbering }}</detail-list-item>
      </detail-list>
    </a-card>

    <a-card :bordered="false">
      <a-row
        v-if="!state.isEdit"
        v-for="(item) in info.moments"
        :key="item.id"
      >
        <a-col>
          <a-row>
            <a-col><h4>文案: </h4></a-col>
            <a-col>
              <div style="white-space: pre-wrap;">{{ item.content }}</div>
            </a-col>
          </a-row>
        </a-col>
        <a-col>
          <a-row>
            <a-col><h4>图片/视频: </h4></a-col>
            <a-col>
              <a-row :gutter="[12, 12]">
                <a-col :span="8" v-for="attItem in item.attachments" :key="attItem.id">
                  <img v-if="attItem.mime_type.indexOf('image') !== -1" width="100" height="100" :src="attItem.url"/>
                  <video
                    v-if="attItem.mime_type.indexOf('video') !== -1"
                    width="100"
                    height="100"
                    controls
                  >
                    <source :src="attItem.url" :type="attItem.mime_type">
                    您的浏览器不支持Video标签。
                  </video>
                </a-col>
              </a-row>
            </a-col>
          </a-row>
        </a-col>
      </a-row>

      <a-form ref="moments-form" :form="momentsForm" v-show="state.isEdit" @submit="handleMomentsSubmit">
        <a-form-item
          v-for="id in material"
          :key="id"
        >
          <a-form-item
            label="素材文字"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <a-row type="flex" justify="start" :gutter="16">
              <a-col span="21">
                <a-textarea
                  v-decorator="[`material[${id}]['content']`, { rules: [{ type: 'string', required: true, message: '请填写文字素材' }] }]"
                />
              </a-col>

              <a-col>
                <a-icon
                  :style="{ fontSize: '25px', 'margin-right': '10px' }"
                  type="minus-circle"
                  @click="delMaterial(id)"/>
              </a-col>
            </a-row>
          </a-form-item>
          <a-form-item
            label="素材图片/视频"
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
          >
            <upload-pic
              :limit="9"
              accept=".jpg,.png,.jpeg,.mp4"
              :size="30 * (1024 ** 2)"
              v-decorator="[`material[${id}]['attachments']`, { rules: [{ type: 'array', required: true, message: '请上传图片/视频素材' }], initialValue: [] }]"
            />
          </a-form-item>
        </a-form-item>

        <a-form-item>
          <a-row type="flex" justify="start" :gutter="24">
            <a-col>
              <a-button type="primary" htmlType="submit" :loading="state.submitLoading">保存</a-button>
            </a-col>
            <a-col>
              <a-button type="primary" @click="addMaterial" v-if="state.isEdit">新增素材</a-button>
            </a-col>
          </a-row>
        </a-form-item>
      </a-form>

      <a-button
        type="primary"
        @click="handleEdit"
        v-show="!state.isEdit"
      >编辑
      </a-button>
    </a-card>
  </div>
</template>

<script>
import DetailList from '@/components/DescriptionList/DescriptionList'
import {
  getCommodityActivityLiveTodayInfo,
  saveCommodityActivityLiveTodayMomentsMaterialSettings
} from '@/api/commodity'
import moment from 'moment'
import UploadPic from '@/components/UploadPic/UploadPic'
import Vue from 'vue'
import clonedeep from 'lodash.clonedeep'

// eslint-disable-next-line no-unused-vars
const DetailListItem = DetailList.Item

const STATUS_MAP = {
  1: '已上架',
  2: '已下架'
}

let currentSelfIncreasingMaterialId = 10

export default {
  name: 'ForwardMaterial',
  components: { UploadPic, DetailList, DetailListItem },
  computed: {
    status () {
      let status = STATUS_MAP[this.info.status]
      if (!moment().isBetween(moment(this.info.panic_buying_start_time), moment(this.info.panic_buying_end_time))) {
        status = '已结束'
      }
      return status
    }
  },
  data () {
    return {
      labelCol: {
        xs: { span: 3 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 12 }
      },

      queryParam: {},
      info: {},
      state: {
        isEdit: false,
        submitLoading: false
      },
      material: [],
      materialDetail: {},

      momentsForm: this.$form.createForm(this)
    }
  },
  created () {
    if (this.$route.params.id) {
      this.getCommodityActivityLiveTodayInfo()
    }
  },
  methods: {
    handleMomentsSubmit (e) {
      e.preventDefault()
      if (this.material.length === 0) {
        this.$message.error('请添加朋友圈素材')
        return false
      }
      this.state.submitLoading = true

      this.momentsForm.validateFields((err, val) => {
        if (err) {
          this.state.submitLoading = false
          return false
        }

        // 根据 material 获取值
        const materialTemp = clonedeep(val.material)
        const values = { moments: [] }
        this.material.forEach(id => {
          values.moments.push({
            content: materialTemp[id].content,
            material: materialTemp[id].attachments.map(att => att.response.id)
          })
        })

        saveCommodityActivityLiveTodayMomentsMaterialSettings(this.$route.params.id, values)
          .then(res => {
            this.getCommodityActivityLiveTodayInfo()
              .finally(_ => {
                this.state.submitLoading = false
                this.state.isEdit = false
                this.$notification.success({ message: '保存成功!' })
              })
          })
          .catch(_ => {
            this.state.submitLoading = false
          })
      })
    },
    addMaterial () {
      this.material.push(currentSelfIncreasingMaterialId++)
    },
    delMaterial (id) {
      Vue.delete(this.material, this.material.indexOf(id))
    },
    handleEdit () {
      this.state.isEdit = true

      // 初始化
      this.material = [] // 对象属性不保证顺序,用不了 key 排序,这里用数组排序

      const res = this.info
      // 添加素材 DOM
      res.hasOwnProperty('moments') && res.moments.forEach(item => {
        this.addMaterial()
      })

      // 表单赋值
      let currentMaterialId = currentSelfIncreasingMaterialId - res.moments.length
      res.moments.map(item => {
        const pic = item.attachments

        this.$nextTick(_ => {
          this.momentsForm.setFieldsValue({
            [`material[${currentMaterialId}]['attachments']`]: pic.map(picItem => ({
              url: picItem.url,
              response: { id: picItem.id, url: picItem.url },
              mime_type: picItem.mime_type || '',
              uid: picItem.id,
              name: picItem.id.toString()
            })),
            [`material[${currentMaterialId}]['content']`]: item.content
          })

          currentMaterialId++
        })
      })
    },
    getCommodityActivityLiveTodayInfo () {
      return new Promise((resolve, reject) => {
        getCommodityActivityLiveTodayInfo(this.$route.params.id).then(res => {
          this.info = res
        }).finally(_ => resolve())
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>
